package com.cssl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cssl.pojo.*;
import com.cssl.pojo.Collections;
import com.cssl.service.*;
import com.cssl.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class AdminController {
    @Autowired
    private UserService service;
    @Autowired
    private PetinfoService service1;

    @Autowired
    private ScoreService service2;

    @Autowired
    private UserpetService service3;
    @Autowired
    private MessageService service4;

    @Autowired
    private SeekService service5;

    @Autowired
    private FoundService service6;
    @Autowired
    private ForumService service7;
    @Autowired
    private ReviewService service8;

    @Autowired
    private CollectionService service9;

    @Autowired
    private LikeService service10;

    @Autowired
    private OrderService service11;

    @Autowired
    private AdoptService service12;

    @Autowired
    private PetshopService service13;



    @Autowired
    private RedisUtil redisUtil;
    //全部用户信息
    @RequestMapping("/userall")
    public IPage<User> userall(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<User> lqw = Wrappers.lambdaQuery();
        lqw.like(User::getUsername,map.get("username").toString());
        lqw.orderByDesc(User::getIsadmin);
        return service.page(new Page<>(index,13),lqw);
    }

    //删除用户（逻辑删除） 或 启用
    @RequestMapping("/deladmin")
    public Boolean deladmin(@RequestParam Integer uid,@RequestParam Integer isdel){
        User u = new User();
        u.setUid(uid);
        if(isdel == 0){
            u.setIsdel(1);
        }
        if(isdel == 1){
            u.setIsdel(0);
        }
        return service.updateById(u);
    }

    //退出后台
    @RequestMapping("/overuser")
    public Boolean overuser(){
        //redis对象集合转换为user存储集合
        List<User> user1 = new ArrayList<>();
        //注销用户后其他在线用户集合
        List<User> user2 = new ArrayList<>();
        List<Object> list = redisUtil.lRange("users",0,100);
        User u = (User)redisUtil.get("admin");
        for (Object o:list) {
            if (o instanceof User){
                user1.add((User) o);
            }
        }
        for (User u1:user1) {
            //判断是否同一用户
            if (!u.getUsername().equals(u1.getUsername())){
                user2.add(u1);
            }
        }
        redisUtil.remove("admin");
        redisUtil.remove("users");
        //存储在线用户集合
        if (user2.size() > 0) {
            redisUtil.rPushAll("users", user2, 60 * 60 * 24);
        }
        return true;
    }

    //管理员信息显示
    @RequestMapping("/admindetail")
    public User admindetail() {
        User u1 =(User)redisUtil.get("admin");
        return service.getById(u1.getUid());
    }


    //修改管理员信息(上传图片)
    @RequestMapping("/upadmin1")
    public Boolean upadmin1(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map) throws ParseException, IOException {
        User u1 =(User)redisUtil.get("admin");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("borndate").toString());
        User u =new User();
        u.setSex(map.get("sex").toString());
        u.setPhone(map.get("phone").toString());
        u.setEmail(map.get("email").toString());
        u.setBorndate(date);
        u.setUsername(map.get("username").toString());
        u.setFaddress(map.get("adrs").toString());
        u.setUid(u1.getUid());
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        u.setFilename(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            Boolean bl = service.updateById(u);
            if(bl){
                //redis对象集合转换为user存储集合
                List<User> user1 = new ArrayList<>();
                //注销用户后其他在线用户集合
                List<User> user2 = new ArrayList<>();
                List<Object> list = redisUtil.lRange("users",0,100);
                for (Object o:list) {
                    if (o instanceof User){
                        user1.add((User) o);
                    }
                }
                for (User u2:user1) {
                    //判断是否同一用户
                    if (u.getUid() == u2.getUid()){
                        continue;
                    }
                    user2.add(u2);
                }
                user2.add(service.getById(u.getUid()));
                redisUtil.remove("admin");
                redisUtil.set("admin",service.getById(u1.getUid()));
                redisUtil.remove("users");
                //存储在线用户集合
                if (user2.size() > 0) {
                    redisUtil.rPushAll("users", user2, 60 * 60 * 24);
                }
                return true;
            }
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //修改管理员信息
    @RequestMapping("/upadmin2")
    public Boolean upadmin2(@RequestParam Map<String, Object> map) throws ParseException{
        User u1 =(User)redisUtil.get("admin");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("borndate").toString());
        User u =new User();
        u.setSex(map.get("sex").toString());
        u.setPhone(map.get("phone").toString());
        u.setEmail(map.get("email").toString());
        u.setBorndate(date);
        u.setUsername(map.get("username").toString());
        u.setFaddress(map.get("adrs").toString());
        u.setUid(u1.getUid());
        Boolean bl = service.updateById(u);
        if(bl){
            //redis对象集合转换为user存储集合
            List<User> user1 = new ArrayList<>();
            //注销用户后其他在线用户集合
            List<User> user2 = new ArrayList<>();
            List<Object> list = redisUtil.lRange("users",0,100);
            for (Object o:list) {
                if (o instanceof User){
                    user1.add((User) o);
                }
            }
            for (User u2:user1) {
                //判断是否同一用户
                if (u.getUid() == u2.getUid()){
                   continue;
                }
                user2.add(u2);
            }
            user2.add(service.getById(u.getUid()));
            redisUtil.remove("admin");
            redisUtil.set("admin",service.getById(u1.getUid()));
            redisUtil.remove("users");
            //存储在线用户集合
            if (user2.size() > 0) {
                redisUtil.rPushAll("users", user2, 60 * 60 * 24);
            }
            return true;
        }
        return false;
    }

    //添加宠物品种(上传图片)
    @RequestMapping("/addpetinfo1")
    public Boolean addpetinfo1(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map) throws IOException {
        Petinfo pn = new Petinfo();
        pn.setBname(map.get("bname").toString());
        pn.setBtype(Integer.parseInt(map.get("type").toString()));
        pn.setHeight(map.get("sg").toString());
        pn.setIq(Integer.parseInt(map.get("iq").toString()));
        pn.setLife(map.get("sm").toString());
        pn.setNickname(map.get("nick").toString());
        pn.setOrigin(map.get("ycd").toString());
        pn.setWeight(map.get("tz").toString());
        pn.setHairlen(map.get("mc").toString());
        pn.setShape(map.get("tx").toString());
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        pn.setBfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service1.save(pn);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //添加宠物品种
    @RequestMapping("/addpetinfo2")
    public Boolean addpetinfo2(@RequestParam Map<String, Object> map){
        Petinfo pn = new Petinfo();
        pn.setBname(map.get("bname").toString());
        pn.setBtype(Integer.parseInt(map.get("type").toString()));
        pn.setHeight(map.get("sg").toString());
        pn.setIq(Integer.parseInt(map.get("iq").toString()));
        pn.setLife(map.get("sm").toString());
        pn.setNickname(map.get("nick").toString());
        pn.setOrigin(map.get("ycd").toString());
        pn.setWeight(map.get("tz").toString());
        pn.setHairlen(map.get("mc").toString());
        pn.setShape(map.get("tx").toString());
        return service1.save(pn);
    }

    //查看评分
    @RequestMapping("/lookscore")
    public Score lookscore(@RequestParam Integer bid){
        LambdaQueryWrapper<Score> lqw = Wrappers.lambdaQuery();
        lqw.eq(Score::getB_id,bid);
        return service2.getOne(lqw);
    }

    //验证是否有评分
    @RequestMapping("/yzscore")
    public Boolean addscore(@RequestParam Integer bid){
        LambdaQueryWrapper<Score> lqw = Wrappers.lambdaQuery();
        lqw.eq(Score::getB_id,bid);
        Score sc=service2.getOne(lqw);
        System.out.println("score:"+sc);
        if(sc != null){
            return true;
        }
        return false;
    }

    //添加评分
    @RequestMapping("/addscore")
    public Boolean addscore(@RequestParam Map<String,Object> map){
        Score sc = new Score();
        sc.setB_id(Integer.parseInt(map.get("bid").toString()));
        sc.setActive(Integer.parseInt(map.get("hy").toString()));
        sc.setOdor(Integer.parseInt(map.get("tw").toString()));
        sc.setSpit(Integer.parseInt(map.get("ks").toString()));
        sc.setFriendly(Integer.parseInt(map.get("ys").toString()));
        sc.setHairloss(Integer.parseInt(map.get("dm").toString()));
        sc.setBeauty(Integer.parseInt(map.get("mr").toString()));
        sc.setSticky(Integer.parseInt(map.get("nr").toString()));
        sc.setTeachable(Integer.parseInt(map.get("kx").toString()));
        sc.setYell(Integer.parseInt(map.get("xj").toString()));
        return service2.save(sc);
    }

    //添加评分
    @RequestMapping("/upscore")
    public Boolean upscore(@RequestParam Map<String,Object> map){
        Score sc = new Score();
        LambdaQueryWrapper<Score> lqw = Wrappers.lambdaQuery();
        lqw.eq(Score::getB_id,Integer.parseInt(map.get("bid").toString()));
        Score s1 = service2.getOne(lqw);
        sc.setSid(s1.getSid());
        sc.setActive(Integer.parseInt(map.get("hy").toString()));
        sc.setOdor(Integer.parseInt(map.get("tw").toString()));
        sc.setSpit(Integer.parseInt(map.get("ks").toString()));
        sc.setFriendly(Integer.parseInt(map.get("ys").toString()));
        sc.setHairloss(Integer.parseInt(map.get("dm").toString()));
        sc.setBeauty(Integer.parseInt(map.get("mr").toString()));
        sc.setSticky(Integer.parseInt(map.get("nr").toString()));
        sc.setTeachable(Integer.parseInt(map.get("kx").toString()));
        sc.setYell(Integer.parseInt(map.get("xj").toString()));
        return service2.updateById(sc);
    }

    //删除评分
    @RequestMapping("/delscore")
    public Boolean delscore(@RequestParam Integer bid){
        LambdaQueryWrapper<Score> lqw = Wrappers.lambdaQuery();
        lqw.eq(Score::getB_id,bid);
        return service2.remove(lqw);
    }

    //修改宠物品种(上传图片)
    @RequestMapping("/uppetinfo1")
    public Boolean uppetinfo1(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map) throws IOException {
        Petinfo pn = new Petinfo();
        pn.setBid(Integer.parseInt(map.get("bid").toString()));
        pn.setBname(map.get("bname").toString());
        pn.setBtype(Integer.parseInt(map.get("type").toString()));
        pn.setHeight(map.get("sg").toString());
        pn.setIq(Integer.parseInt(map.get("iq").toString()));
        pn.setLife(map.get("sm").toString());
        pn.setNickname(map.get("nick").toString());
        pn.setOrigin(map.get("ycd").toString());
        pn.setWeight(map.get("tz").toString());
        pn.setHairlen(map.get("mc").toString());
        pn.setShape(map.get("tx").toString());
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        pn.setBfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service1.updateById(pn);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //修改宠物品种
    @RequestMapping("/uppetinfo2")
    public Boolean uppetinfo2(@RequestParam Map<String, Object> map){
        Petinfo pn = new Petinfo();
        pn.setBid(Integer.parseInt(map.get("bid").toString()));
        pn.setBname(map.get("bname").toString());
        pn.setBtype(Integer.parseInt(map.get("type").toString()));
        pn.setHeight(map.get("sg").toString());
        pn.setIq(Integer.parseInt(map.get("iq").toString()));
        pn.setLife(map.get("sm").toString());
        pn.setNickname(map.get("nick").toString());
        pn.setOrigin(map.get("ycd").toString());
        pn.setWeight(map.get("tz").toString());
        pn.setHairlen(map.get("mc").toString());
        pn.setShape(map.get("tx").toString());
        return service1.updateById(pn);
    }

    //删除单个品种
    @RequestMapping("/delpetinfo")
    public Boolean delpetinfo(@RequestParam Integer bid){
        return service1.removeById(bid);
    }

    //显示用户宠物
    @RequestMapping("/userpetall")
    public IPage<Userpet> userpetall(@RequestParam Map<String,Object> map){
        LambdaQueryWrapper<Userpet> lqw = Wrappers.lambdaQuery();
        lqw.like(Userpet::getUpname,map.get("upname").toString());
        lqw.orderByAsc(Userpet::getUpid);
        return service3.page(new Page<>(Integer.parseInt(map.get("index").toString()),13),lqw);
    }
    //单条信息显示
    @RequestMapping("/userpetone")
    public Userpet userpetone(@RequestParam Integer upid){
        return service3.getById(upid);
    }


    //显示所有信息
    @RequestMapping("/messageall")
    public IPage<Message> messageall(@RequestParam Map<String,Object> map){
        int type =Integer.parseInt(map.get("type").toString());
        LambdaQueryWrapper<Message> lqw = Wrappers.lambdaQuery();
        if(type == 1){
            //来领养
           lqw.ne(Message::getC_aid,0);
        }else if(type == 2){
            //来寻宠
            lqw.ne(Message::getC_seekid,0);
        }else if(type == 3){
            //来招领
            lqw.ne(Message::getC_fid,0);
        }
        lqw.orderByAsc(Message::getCid);
        return service4.page(new Page<>(Integer.parseInt(map.get("index").toString()),13),lqw);
    }

    //单条信息显示
    @RequestMapping("/msgone")
    public Message messageall(@RequestParam Integer cid){
        return service4.getById(cid);
    }

    //删除信息
    @RequestMapping("/delmsg")
    public Boolean delmsg(@RequestParam Integer cid){
        return service4.removeById(cid);
    }

    //寻宠启事
    @RequestMapping("/seekall2")
    public IPage<Seek> seekall2(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Seek> lqw = Wrappers.lambdaQuery();
        lqw.like(Seek::getSeekaddress,map.get("address").toString());
        lqw.orderByDesc(Seek::getSeekdate);
        return service5.page(new Page<>(index,13),lqw);
    }
    //单个寻宠详情
    @RequestMapping("/seekone")
    public Seek seekone(@RequestParam Integer seekid){
        return service5.getById(seekid);
    }
    //删除寻宠
    @RequestMapping("/delseekone")
    public Boolean delseekone(@RequestParam Integer seekid){
        return service5.removeById(seekid);
    }

    //招领启事
    @RequestMapping("/foundall2")
    public IPage<Found> foundall2(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Found> lqw = Wrappers.lambdaQuery();
        lqw.like(Found::getFoundaddress,map.get("address").toString());
        lqw.orderByDesc(Found::getFounddate);
        return service6.page(new Page<>(index,13),lqw);
    }
    //单个招领详情
    @RequestMapping("/foundone")
    public Found foundone(@RequestParam Integer fid){
        return service6.getById(fid);
    }
    //删除招领
    @RequestMapping("/delfoundone")
    public Boolean delfoundone(@RequestParam Integer fid){
        return service6.removeById(fid);
    }

    //全部帖子
    @RequestMapping("/bbsAll2")
    public IPage<Forum> bbsAll2(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Forum> lqw  = Wrappers.lambdaQuery();
        lqw.like(Forum::getForumtitle,map.get("title").toString());
        lqw.orderByDesc(Forum::getFbdate);
        return service7.page(new Page<>(index,13),lqw);
    }

    //修改帖子状态
    @RequestMapping("/upbbsstu")
    public Boolean upbbsstu(@RequestParam Map<String,Object> map){
        Forum fm = new Forum();
        fm.setForumid(Integer.parseInt(map.get("forumid").toString()));
        fm.setFb_audit(Integer.parseInt(map.get("stu").toString()));
        return service7.updateById(fm);
    }

    //删除贴子  连同评论
    @RequestMapping("/delbbs")
    public Boolean delbbs(@RequestParam Integer forumid){
        LambdaQueryWrapper<Review> lqw = Wrappers.lambdaQuery();
        lqw.eq(Review::getR_forumid,forumid);
       service8.remove(lqw);
       return service7.removeById(forumid);
    }
    //全部收藏
    @RequestMapping("/reviewAll")
    public IPage<Review> reviewAll(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Review> lqw  = Wrappers.lambdaQuery();
        lqw.orderByDesc(Review::getRedate);
        return service8.page(new Page<>(index,13),lqw);
    }

    //单个评论详情
    @RequestMapping("/reviewone")
    public Review reviewAll(@RequestParam Integer reviewid){
        return service8.getById(reviewid);
    }


    //全部收藏
    @RequestMapping("/collAll")
    public IPage<Collections> collAll(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Collections> lqw  = Wrappers.lambdaQuery();
        lqw.orderByDesc(Collections::getCodate);
        return service9.page(new Page<>(index,13),lqw);
    }

    //全部点赞
    @RequestMapping("/likeall")
    public IPage<Like> likeall(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Like> lqw  = Wrappers.lambdaQuery();
        lqw.orderByDesc(Like::getLikedate);
        return service10.page(new Page<>(index,13),lqw);
    }

    //全部订单
    @RequestMapping("/orderall")
    public IPage<Orders> orderall(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Orders> lqw  = Wrappers.lambdaQuery();
        lqw.like(Orders::getOrderid,map.get("orderid").toString());
        lqw.eq(Orders::getIsdel,0);
        lqw.orderByDesc(Orders::getOdate);
        return service11.page(new Page<>(index,13),lqw);
    }

    //删除店铺（逻辑删除）
    @RequestMapping("/delshop")
    public Boolean delshop(@RequestParam Integer psid,@RequestParam Integer isdel){
        Petshop ps = new Petshop();
        ps.setIsdel(isdel);
        ps.setPsid(psid);
        return service13.updateById(ps);
    }

    //店铺详情
    @RequestMapping("/petshopone")
    public Petshop petshopone(@RequestParam Integer psid){
        return service13.getById(psid);
    }


}
